package cn.source.system.asp;

import cn.source.common.constant.HttpStatus;
import cn.source.common.core.domain.model.H5LoginUser;
import cn.source.framework.web.service.TokenH5Service;
import io.jsonwebtoken.ExpiredJwtException;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 记录调用Controller的日志
 */
@Component
@Aspect
public class AuthAspect {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private TokenH5Service tokenH5Service;

    @Pointcut("execution(* cn.source.system.controller.api..*.*(..)) && !@annotation(cn.source.system.asp.NoNeedCheck)")
    public void before() {
    }

    @Before("before()")
    public void beforeLogin(JoinPoint joinPoint) throws ServiceException {
        try {
            // 接收到请求，记录请求内容
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            //为测试方便 当token没传时在session获取
            HttpServletRequest httpServletRequest = attributes.getRequest();
            H5LoginUser h5LoginUser = tokenH5Service.getLoginUser(httpServletRequest);
            if (h5LoginUser == null) {
                throw new AccessDeniedException("请登录");
            }
            tokenH5Service.refreshToken(h5LoginUser);
            UserH5ContextHandler.set(h5LoginUser);
        } catch (ServiceException e) {
            throw e;
        } catch (ExpiredJwtException e) {
            throw new AccessDeniedException("请登录");
        } catch (Exception e) {
            throw new AccessDeniedException("请登录");
        }
    }


}